package cc.dawning.utiming.lklocation.location.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import cc.dawning.utiming.lklocation.R;
import cc.dawning.utiming.lklocation.location.adapter.LocationAdapter;
import cc.dawning.utiming.lklocation.location.api.LocationEventListener;
import cc.dawning.utiming.lklocation.location.global.LocationHandler;
import cc.dawning.utiming.lklocation.location.global.LocationHandlerKey;
import cc.dawning.utiming.lklocation.location.utils.LocationPermissionUtil;
import cc.dawning.utiming.lklocation.location.utils.SaveScreenUtils;
import cc.dawning.utiming.lklocation.location.view.LocationLoading;
import cc.dawning.utiming.lklocation.location.view.SearchDialog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cc.vv.baselibrary.activity.UtimingBaseActivity;
import cc.vv.baselibrary.location.LocationChooseObj;
import cc.vv.baselibrary.location.LocationIntentKey;
import cc.vv.lkbasecomponent.util.LKScreenUtil;


/**
 * Created by Administrator on 2016/6/27
 * 定位
 */
public class LocationSourceActivity extends UtimingBaseActivity implements LocationSource,
        View.OnClickListener,
        LocationEventListener {
    /**
     * 返回按钮
     */
    private LinearLayout rl_vtb_left_layout_location;
    /**
     * 确认按钮
     */
    private LinearLayout ll_submit;
    /**
     * 搜索按钮
     */
    private LinearLayout ll_serch;
    /**
     * 地图显示View
     */
    private MapView mapView;
    /**
     * 地图定位中间显示点父布局
     */
    private LinearLayout Lin_group;
    /**
     * 中间显示View
     */
    private View centerPoint;
    /**
     * 中间显示图片
     */
    private ImageView Iv_center;
    /**
     * 显示地图父布局
     */
    private RelativeLayout rel_mapView;
    /**
     * POI推荐位置显示列表
     */
    private ListView lv_location;
    /**
     * 选择标识
     */
    private ImageView iv_check;
    /**
     * 当前定位位置显示按钮
     */
    private TextView tv_location;
    /**
     * 无数据展示
     */
    private RelativeLayout rl_no_data;
    /**
     * 定位按钮
     */
    private ImageView Iv_location;


    private LocationAdapter adapter;
    private GeocodeSearch geocodeSearch;
    private double weidu;
    private double jingdu;
    /**
     * 纬度
     */
    private double Latitude;
    /**
     * 经度
     */
    private double Longitude;
    /**
     * 定位地址
     */
    private String addressTitle;
    /**
     * 搜索的页数
     */
    private int page = 1;
    /**
     * 刚进入页面定位的经纬度,没有移动MapView
     */
    private LatLng latlng = null;
    /**
     * 返回搜索周边数据的集合
     */
    private ArrayList<PoiItem> dataList = new ArrayList<>();
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    /**
     * Poi查询条件类
     */
    private PoiSearch.Query query;
    /**
     * 定位监听
     */
    private MyLocationListener mMyLocationListener;
    /**
     * 搜索周边监听
     */
    private SearchListener mSearchListener;
    /**
     * 拖动View定位显示在屏幕正中间监听
     */
    private CameraChangerListener mCameraChangerListener;
    /**
     * 城市编码
     */
    private String cityCode;
    private String search_title;
    /**
     * 点击了Item
     */
    private boolean isCheckItem = false;
    private int currPos = 0;
    /**
     * 将经纬度转换为详细地址
     */
    private MyGeocodeSearchListener mMyGeocodeSearch;
    private PoiSearch poiSearch;
    /**
     * 手机设备当前所在的地址
     */
    private String local_address;
    private boolean isInterFirst = true;
    private boolean isLoadMore;
    private int total = 0;
    private String addressName;
    private boolean isResult = false;
    private Geocoder geocoder;
    /**
     * 没有周围数据时的定位信息
     */
    private String noDataAddress = " ";
    private String selectName = " ";
    private boolean isLoading;
    /**
     * 通知handler
     */
    private LocationHandler locationHandler;
    private String ipAndPort = "https://file.botong.tech/";
    private LocationLoading loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        //文件上传IP + port
        ipAndPort = getIntent().getStringExtra(LocationIntentKey.FILE_UPLOAD_IP_PORT);
        initView();
        initMap();
        initViewEvent();
        initListener();
        LocationPermissionUtil.getInstance().requestAll(this);
        // 此方法必须重写
        mapView.onCreate(savedInstanceState);
        loading = new LocationLoading(R.layout.view_location_loading);
        //初始化加载框
        loading.initLoadingView(this);
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        super.initView(bundle);
    }


    /**
     * 初始化map
     */
    private void initMap() {
        init();
        int width = LKScreenUtil.getScreenWidth();
        int screenHeight = width * 3 / 4;
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rel_mapView.getLayoutParams();
        layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
        layoutParams.height = screenHeight;
        rel_mapView.setLayoutParams(layoutParams);
        geocoder = new Geocoder(this, Locale.getDefault());
    }

    /**
     * 初始化view
     */
    @SuppressLint("ClickableViewAccessibility")
    protected void initView() {
        rl_vtb_left_layout_location = findViewById(R.id.rl_vtb_left_layout_location);
        ll_submit = findViewById(R.id.rl_vtb_right_layout_location);
        ll_serch = findViewById(R.id.ll_serch);
        mapView = findViewById(R.id.mapView);
        Lin_group = findViewById(R.id.Lin_group);
        centerPoint = findViewById(R.id.centerPoint);
        Iv_center = findViewById(R.id.Iv_center);
        rel_mapView = findViewById(R.id.Rel_mapview);
        lv_location = findViewById(R.id.lv_location);
        iv_check = findViewById(R.id.iv_check);
        tv_location = findViewById(R.id.tv_location);
        rl_no_data = findViewById(R.id.rl_no_data);
        Iv_location = findViewById(R.id.Iv_location);

        //设置确认按钮不可点击,当定位成功后按钮才可点击
        ll_submit.setClickable(false);
        ll_submit.setVisibility(View.GONE);
    }

    /**
     * 初始化数据
     */
    protected void initViewEvent() {
        //初始化适配器
        adapter = new LocationAdapter(dataList, LocationSourceActivity.this);
        lv_location.setAdapter(adapter);
        adapter.getIsSelected().put(0, true);
        //初始化handler
        locationHandler = new LocationHandler(this);
        //推荐列表点击
        lv_location.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isLoading) {
                    Toast.makeText(LocationSourceActivity.this, "数据提交中,请稍后...", Toast.LENGTH_SHORT).show();
                    return;
                }
                isCheckItem = true;
                currPos = position;
                for (int i = 0; i < dataList.size(); i++) {
                    adapter.getIsSelected().put(i, false);
                }
                adapter.getIsSelected().put(position, true);
                PoiItem poil = dataList.get(position);
                addMaker_two(poil.getLatLonPoint().getLatitude(), poil.getLatLonPoint().getLongitude(), false);
                LatLng ll = new LatLng(poil.getLatLonPoint().getLatitude(), poil.getLatLonPoint().getLongitude());
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(ll));
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, 16));
                adapter.notifyDataSetChanged();
            }
        });

    }

    /**
     * 设置按钮点击监听
     */
    private void initListener() {
        rl_vtb_left_layout_location.setOnClickListener(this);
        ll_serch.setOnClickListener(this);
        ll_submit.setOnClickListener(this);
        Iv_location.setOnClickListener(this);
    }


    private void addMaker_two(double latitude, double longitude, boolean isShowNew) {
        aMap.clear();
        aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_yourself_lication)).position(new LatLng(weidu, jingdu)));
        if (isShowNew) {
            aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.icon_yourself_lication)).position(new LatLng(latitude, longitude)));
        }
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (mMyLocationListener == null) {
            mMyLocationListener = new MyLocationListener();
        }
        if (mSearchListener == null) {
            mSearchListener = new SearchListener();
        }
        if (mCameraChangerListener == null) {
            mCameraChangerListener = new CameraChangerListener();
        }
        if (mMyGeocodeSearch == null) {
            mMyGeocodeSearch = new MyGeocodeSearchListener();
        }
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_yourself_lication));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.TRANSPARENT);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0.1f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        // aMap.setMyLocationRotateAngle(180);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setOnCameraChangeListener(mCameraChangerListener);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false); // 设置缩放按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // aMap.setMyLocationType()
        //设置定位间隔,单位毫秒,默认为5000ms
        mLocationOption.setInterval(5000);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(19f)); // 3~19

        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(mMyGeocodeSearch);
    }

    /**
     * 响应逆地理编码
     */
    public void getAddress(final LatLonPoint latLonPoint) {
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 1000, GeocodeSearch.AMAP);
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        geocodeSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }

    /***********************************************************************************/
    /**                                    POI推荐位置搜索                              **/
    /***********************************************************************************/

    /**
     * 开始搜索附近500m的数据
     */
    private void search() {
        ll_submit.setClickable(false);
        //显示加载框
        loading.showLoading();
        query = new PoiSearch.Query("", "汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施", "");
        // keyWord表示搜索字符串，第二个参数表示POI搜索类型，默认为：生活服务、餐饮服务、商务住宅
        // 共分为以下20种：汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|
        // 商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
        // cityCode表示POI搜索区域，（这里可以传空字符串，空字符串代表全国在全国范围内进行搜索）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(1);// 设置查第一页
        poiSearch = new PoiSearch(this, query);
        //如果不为空值
        if (Latitude != 0.0 && Longitude != 0.0) {
            poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(Latitude, Longitude), 3000));// 设置周边搜索的中心点以及区域
            poiSearch.setOnPoiSearchListener(mSearchListener);// 设置数据返回的监听器
            poiSearch.searchPOIAsyn();// 开始搜索
        }
    }

    /**
     * 实现搜索周边的监听
     */
    private class SearchListener implements PoiSearch.OnPoiSearchListener {

        @Override
        public void onPoiSearched(PoiResult poiResult, int i) {
            //关闭加载框
            loading.closeLoading();
            if (isLoadMore) {
                ArrayList<PoiItem> pois = poiResult.getPois();
                if (pois.size() == 0) {
                    addressTrans();
                    ll_submit.setVisibility(View.GONE);
                    rl_no_data.setVisibility(View.VISIBLE);
                    lv_location.setVisibility(View.GONE);
                    tv_location.setText(noDataAddress);
                    locationHandler.sendEmptyMessage(LocationHandlerKey.LOAD_MORE_DATA);
                } else {
                    ll_submit.setVisibility(View.VISIBLE);
                    rl_no_data.setVisibility(View.GONE);
                    lv_location.setVisibility(View.VISIBLE);
                    dataList.addAll(pois);
                    locationHandler.sendEmptyMessage(LocationHandlerKey.LOAD_MORE_DATA);
                }
            } else {
                ArrayList<PoiItem> pois = poiResult.getPois();
                if (pois.size() == 0) {
                    addressTrans();
                    rl_no_data.setVisibility(View.VISIBLE);
                    lv_location.setVisibility(View.GONE);
                    tv_location.setText(noDataAddress);
                    locationHandler.sendEmptyMessage(LocationHandlerKey.REFRESH_DATA);
                    ll_submit.setVisibility(View.GONE);
                } else {
                    ll_submit.setVisibility(View.VISIBLE);
                    rl_no_data.setVisibility(View.GONE);
                    lv_location.setVisibility(View.VISIBLE);
                    dataList.clear();
                    dataList.addAll(pois);
                    locationHandler.sendEmptyMessage(LocationHandlerKey.REFRESH_DATA);
                }
            }
        }

        @Override
        public void onPoiItemSearched(PoiItem poiItem, int i) {

        }
    }
    /***********************************************************************************/
    /**                                    地图定位                                    **/
    /***********************************************************************************/

    /**
     * 定位实现LocationSource接口开始重写的两个方法。
     *
     * @param onLocationChangedListener 位置变化监听
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(mMyLocationListener);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mLocationClient.startLocation();
        }
    }

    /**
     * 定位实现LocationSource接口的方法结束。
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    /**
     * 定位监听
     */
    private class MyLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {

            if (mListener != null && amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    // 显示系统小蓝点
                    mListener.onLocationChanged(amapLocation);
                    //获取纬度
                    double Latitude = amapLocation.getLatitude();
                    //获取经度
                    double Longitude = amapLocation.getLongitude();
                    latlng = new LatLng(Latitude, Longitude);
                    weidu = Latitude;
                    jingdu = Longitude;
                    cityCode = amapLocation.getCityCode();
                    local_address = amapLocation.getAddress();
                } else {
                    Toast.makeText(LocationSourceActivity.this, "定位失败, 请检查权限是否开启", Toast.LENGTH_SHORT).show();
                    loading.closeLoading();
                }
            }
        }
    }

    /**
     * 拖动mapView使得定位销蓝点始终显示在屏幕正中间位置
     */
    private class CameraChangerListener implements AMap.OnCameraChangeListener {

        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
            //显示loading
            if (!isCheckItem) {
//                loading.showLoading();
            }
        }

        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {
            total++;
            if (isCheckItem) {
                return;
            }
            if (isInterFirst) {
                isInterFirst = false;
                return;
            }
            if (isResult && total > 1) {
                return;
            }
            addMaker_two(0, 0, false);
            //获取纬度
            Latitude = cameraPosition.target.latitude;
            //获取经度
            Longitude = cameraPosition.target.longitude;
            LatLonPoint lp = new LatLonPoint(Latitude, Longitude);
            getAddress(lp);
        }
    }

    /**
     * 将经纬度转换成具体地址信息。
     */
    private class MyGeocodeSearchListener implements GeocodeSearch.OnGeocodeSearchListener {

        @Override
        public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
            if (rCode == 1000) {
                if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
                    if (isResult) {
                        addressName = search_title;
                    } else {
                        addressName = result.getRegeocodeAddress().getFormatAddress();
                    }
                    search();
                    isLoadMore = false;
                }
            }
        }

        @Override
        public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {

        }
    }

    /***********************************************************************************/
    /**                                    地图位置选择事件处理                           **/
    /***********************************************************************************/

    @Override
    public void RefrushPOIData(Message msg) {
        for (int i = 0; i < dataList.size(); i++) {
            adapter.getIsSelected().put(i, false);
        }
        adapter.getIsSelected().put(0, true);
        if (dataList.size() > 0) {
            PoiItem p = dataList.get(0);
            p.setDirection(addressName);
            p.getLatLonPoint().setLatitude(Latitude);
        }
        adapter.notifyDataSetChanged();
        loading.closeLoading();
        isResult = false;
        total = 0;
        ll_submit.setClickable(true);
    }

    @Override
    public void LoadMorePOIData(Message msg) {
        adapter.notifyDataSetChanged();
        loading.closeLoading();
        isResult = false;
        total = 0;
        ll_submit.setClickable(true);
    }


    @Override
    public void SearchListener(Message msg) {
        Tip tip = (Tip) msg.obj;
        if (null != tip) {
            isCheckItem = false;
            isResult = true;
            total = 0;
            ll_submit.setClickable(false);
            if (null != tip.getPoint()) {
                Latitude = tip.getPoint().getLatitude();
                Longitude = tip.getPoint().getLongitude();
            }
            search_title = tip.getDistrict() + tip.getName();
            addMaker_two(Latitude, Longitude, false);
            LatLng ll = new LatLng(Latitude, Longitude);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(ll));
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, 16));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onClick(View v) {
        isLoading = false;
        if (isLoading) {
            Toast.makeText(this, "数据提交中,请稍后...", Toast.LENGTH_SHORT).show();
            return;
        } else {
            int id = v.getId();
            if (id == R.id.Iv_location) {
                //我的位置
                isCheckItem = false;
                if (null != latlng) {
                    currPos = 0;
                    addMaker_two(0, 0, false);
                    addressTitle = local_address;
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(latlng));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(16f));
                    for (int i = 0; i < dataList.size(); i++) {
                        adapter.getIsSelected().put(i, false);
                    }
                    adapter.getIsSelected().put(0, true);
                    adapter.notifyDataSetChanged();
                }
                lv_location.setSelection(0);
            } else if (id == R.id.rl_vtb_right_layout_location) {
                //确认
                boolean granted = LocationPermissionUtil.getInstance().requestSD(this);
                File file = null;
                if (granted) {
                    file = SaveScreenUtils.saveScreen(rel_mapView);
                } else {
                    Toast.makeText(this, "未检测到SD卡权限,请打开权限后重新定位", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!TextUtils.isEmpty(noDataAddress)) {
                    //上传服务器
                } else {
                    Toast.makeText(this, "正在定位,请稍后再试", Toast.LENGTH_SHORT).show();
                }
            } else if (id == R.id.ll_serch) {
                //搜索
                SearchDialog.getInstance().showSearchDialog(LocationSourceActivity.this, ll_serch);
            } else if (id == R.id.rl_vtb_left_layout_location) {
                //取消
                finish();
            } else {
                return;
            }
        }
    }

    @Override
    protected void onRequestSuccess(String url, Object obj) {
        super.onRequestSuccess(url, obj);
        isLoading = true;

    }

    @Override
    protected void onRequestFailure(String url, boolean isLoading, String exceptionStr) {
        super.onRequestFailure(url, isLoading, exceptionStr);
        this.isLoading = true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null && resultCode == 101) {
            isCheckItem = false;
            isResult = true;
            total = 0;
            ll_submit.setClickable(false);
            Latitude = data.getDoubleExtra(LocationIntentKey.LOCATION_LATITUDE, 0);
            Longitude = data.getDoubleExtra(LocationIntentKey.LOCATION_LONGITUDE, 0);
            search_title = data.getStringExtra(LocationIntentKey.LOCATION_TITLE_TEXT);
            addMaker_two(Latitude, Longitude, false);
            LatLng ll = new LatLng(Latitude, Longitude);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(ll));
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, 16));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LocationPermissionUtil.REQUEST_PERMISSION_SD) {
            //SD卡请求权限
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ll_submit.setClickable(true);
            } else {
                Toast.makeText(this, "未检测到SD卡权限,请打开权限后重新定位", Toast.LENGTH_SHORT).show();
                ll_submit.setClickable(true);
            }
        } else if (requestCode == LocationPermissionUtil.REQUEST_PERMISSION_FILESYSTEMS) {
            //全部权限 定位权限
            if (grantResults[2] == PackageManager.PERMISSION_GRANTED && grantResults[3] == PackageManager.PERMISSION_GRANTED) {
                setUpMap();
            } else {
                Toast.makeText(LocationSourceActivity.this, "定位失败, 请检查权限是否开启", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != locationHandler) {
            locationHandler = null;
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 把经纬度转为地址
     */

    private void addressTrans() {
        try {
            List<Address> addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                noDataAddress = address.getAddressLine(0);
            }
        } catch (IOException e) {
            Log.e("location", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 返回选择数据结果
     */
    private void setChooseResultBack(String path, String url, String smallUrl) {
        LocationChooseObj chooseObj = new LocationChooseObj();
        chooseObj.filePath = path;
        //服务器图片地址,暂时为本地图片路径
        chooseObj.imageUrl = TextUtils.isEmpty(url) ? path : url;
        chooseObj.smallImageUrl = TextUtils.isEmpty(smallUrl) ? path : smallUrl;

        PoiItem poiItem = dataList.get(currPos);
        chooseObj.geteraPositionStr = poiItem + "";
        chooseObj.detailPositionStr = poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet();
        chooseObj.latitude = Latitude;
        chooseObj.longtitude = Longitude;
        chooseObj.locationTitle = selectName;
        chooseObj.loationAddress = addressTitle;
        chooseObj.imgWidth = rel_mapView.getWidth();
        chooseObj.imgHeight = rel_mapView.getHeight();

        Intent intent1 = new Intent();
        intent1.putExtra(LocationIntentKey.LOCATION_CHOOSE, chooseObj);
        setResult(RESULT_OK, intent1);
        finish();

    }

    public void showLoadView() {
        loading.showLoading();
    }

    public void hideLoadView() {
        loading.closeLoading();
    }

    public LocationHandler getLocationHandler() {
        return locationHandler;
    }


}